package com.study.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
//@CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)
public class MyController {

    @RequestMapping("/index")
    public String index() {
        return "success";
    }

    @RequestMapping("/preUser")
    //@CrossOrigin("http://127.0.0.1:8080")
    public Map<String, String> preUser(HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");  //用来明确指定那些客户端的域名允许访问这个资源。
        HashMap<String, String> map = new HashMap<>();
        map.put("preUser", "success");
        return map;
    }

    @RequestMapping("/jsonp")   //jsonp 实现跨域
    public void jsonp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("preUser", "success");

        PrintWriter out = response.getWriter();
        JSONObject resultJSON = new JSONObject(map);; //根据需要拼装json
        String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
        out.println(jsonpCallback+"("+resultJSON.toString()+")");//返回jsonp格式数据
        out.flush();
        out.close();

    }

}
